<?php
namespace app\wechat\model;
use think\Model;
use EasyWeChat\Factory;
use think\model\concern\SoftDelete;

class WechatNews extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $defaultSoftDelete = 0;
    protected $autoWriteTimestamp = true;

    protected $globalScope = ['store_id'];
    public function scopeStore_id($query)
    {
        $query->where('store_id', StoreId());
    }

    // 创建素材
    public static function CreateNews($data)
    {
        //循环
        foreach($data['item'] as $r){
            //判断是否添加过
            $media = self::where('media_id',$r['media_id'])->find();
            //没有添加过.继续下一步
            if(!$media){
                //循环添加
                foreach ($r['content']['news_item'] as $k=>$v){
                    $news = $v;
                    $news['store_id'] = StoreId();
                    $news['media_id'] = $r['media_id'];
                    $news['create_time'] = $r['content']['create_time'];
                    $news['update_time'] = $r['content']['update_time'];
                    $news['sort_order'] = $k;
                    self::insert($news);
                }
            }
        }
        return;
    }
    //列出所有关键字
    public static function get_lists()
    {
        $list = self::where('sort_order','0')->order('id desc')->select();
        return $list;
    }
    
    // 同组别文章
    public function groupNews()
    {
        return $this->hasMany(self::class,'media_id','media_id')->order('sort_order asc');
    }
    
    
    
}